<?php

namespace App\Console\Commands\User;

use Illuminate\Console\Command;
use App\Models\User;

class AddUserCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'user:add';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:add
        {username : The username}
        {password : The password}
        {role : The role of the user}
        {fullname? : The fullname of the user, username as default}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Add a new user';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        // 获取参数
        $username = $this->argument('username');
        $password = $this->argument('password');
        $role = $this->argument('role');
        $fullname = $this->argument('fullname');

        // 密码加密
        $password = password_hash($password, PASSWORD_DEFAULT);

        // 检查用户存在性
        $hasUser = User::where('username', $username)->first();
        if ($hasUser) {
            $this->error('User exist!');
        } else {
            // 默认全名
            $fullname = $fullname ? $fullname : $username;
            User::create([
                'username' => $username,
                'password' => $password,
                'role'     => $role,
                'fullname' => $fullname,
            ]);
            $this->info('User created successfully!');
        }
    }
}
